from flask import Flask
from flask_cors import CORS
from paddy_doctor.config import default_config
from flask_login import LoginManager
from paddy_doctor.model.user import User
from paddy_doctor.model.database import mongo


def create_app(config_name='development'):
    # 创建app实例对象
    app = Flask(__name__)
    # 打开CORS
    cors = CORS(app, resources={r"/*": {"origins": "*"}})
    app.config['CORS_HEADERS'] = 'Content-Type'
    # 配置用户登录
    login_manager = LoginManager()
    @login_manager.request_loader
    def load_user_from_request(request):
        '''登录中间件'''
        # try to login using the api_key url arg
        token = request.args.get('token')
        if token:
            user = User.find(token)
            if user:
                return user
        # return None if both methods did not login the user
        return None
    login_manager.init_app(app)
    # 加载配置
    app.config.from_object(default_config)
    app.secret_key = b'cbW\xdd\xdd\xdb\xba3\xd5\xcec\xfcrp\x92D'
    # 连接数据库
    mongo.init_app(app)
    # 挂载蓝图
    from paddy_doctor.views import classifier
    app.register_blueprint(classifier.mod, url_prefix='/classifier')
    from paddy_doctor.views import user
    app.register_blueprint(user.mod, url_prefix='/user')
    # 查看URL映射
    # print(app.url_map)
    return app
